package com.hdu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.entity.Website;
import com.hdu.enums.WebsiteLabel;
import com.hdu.mapper.WebsiteMapper;
import com.hdu.pojo.PageBean;
import com.hdu.pojo.Sort;
import com.hdu.service.IWebsiteService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 网站实体类 服务实现类
 * </p>
 *
 * @author xiaobai
 * @since 2025-02-07
 */
@Service
@RequiredArgsConstructor
public class WebsiteServiceImpl extends ServiceImpl<WebsiteMapper, Website> implements IWebsiteService {

    private final WebsiteMapper websiteMapper;

    /**
     * 网站链接查询
     */
    @Override
    public PageBean<Website> page(Integer current, Integer size, String name) {
        //1. 设置分页参数
        Page<Website> page = new Page<>(current, size);

        QueryWrapper<Website> wrapper = new QueryWrapper<>();
        wrapper.eq(!StrUtil.isEmpty(name), "name", name);

        IPage<Website> iPage = websiteMapper.selectPage(page, wrapper);

        return new PageBean<>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 网站链接分类查询
     */
    @Override
    public List<Sort> sortWebsite() {
        List<Sort> sortList = new ArrayList<>();
        Map<WebsiteLabel, List<Website>> map = list().stream().collect(Collectors.groupingBy(Website::getLabel));
        for (WebsiteLabel websiteLabel : map.keySet()) {
            Sort sort = new Sort(websiteLabel.getDesc(), "", map.get(websiteLabel));
            sortList.add(sort);
        }
        return sortList;
    }

    /**
     * 新增网站链接
     */
    @Override
    public void append(Website website) {
        for (int i = 1; i < 100; i++) {
            Integer id = website.getLabel().getValue() * 100 + i;
            if (websiteMapper.selectById(id) == null) {
                website.setId(id);
                break;
            }
        }
        websiteMapper.insert(website);
    }
}

